var REPORT_VIEW = {};
REPORT_VIEW.baseUrl = "";
REPORT_VIEW.module = {};
REPORT_VIEW.module.VIEW_CREATED ="VIEW_CREATED";
REPORT_VIEW.module.RELATIONSHIP_UPDATE ="RELATIONSHIP_UPDATE";
REPORT_VIEW.module.VIEW_DELETED ="VIEW_DELETED";
REPORT_VIEW.module.REPORT_DESIGNED ="REPORT_DESIGNED";
REPORT_VIEW.module.REPORT_CONSULTED ="REPORT_CONSULTED";
REPORT_VIEW.module.DIV= {};

REPORT_VIEW.module.DIV[REPORT_VIEW.module.VIEW_CREATED] = "<div class='item ng_VIEW_CREATED'><i class='fa fa-plus'></i>新增模版</div>";
REPORT_VIEW.module.DIV[REPORT_VIEW.module.VIEW_DELETED]  = "<div class='item ng_VIEW_DELETED'><i class='fa fa-trash'></i>删除模版</div>";
REPORT_VIEW.module.DIV[REPORT_VIEW.module.RELATIONSHIP_UPDATE]  = "<div class='item ng_RELATIONSHIP_UPDATE'><i class='fa fa-venus-double'></i>数据关系</div>";
REPORT_VIEW.module.DIV[REPORT_VIEW.module.REPORT_DESIGNED] = "<div class='item ng_REPORT_DESIGNED'><i class='fa fa-check'></i>制作报表</div>";
REPORT_VIEW.module.DIV[REPORT_VIEW.module.REPORT_CONSULTED]="<div class='item ng_REPORT_CONSULTED'><i class='fa fa-bars'></i>查看报表</div>";

/*---------------------------*/
REPORT_VIEW.module.initFunc=[];

REPORT_VIEW.VIEW_CREATED = {};
var REPORT_CREATE = REPORT_VIEW.VIEW_CREATED;
function funcOfViewCreated(){
    console.log("--- REPORT_VIEW.module.initFunc first---");
    REPORT_CREATE.expressColumns = new Object();// 公式列组
    REPORT_CREATE.expressColumns.data = new Array();
    REPORT_CREATE.expressColumns.colDefs = new Array();
    REPORT_CREATE.table = new Object();
    REPORT_CREATE.table.data = new Array();//[{key: t_shop ,value :[{key:id,value:10},{}]},{}]
    REPORT_CREATE.table.colDefs = new Array();
    REPORT_CREATE.view = new Object();
    REPORT_CREATE.view.data = new Array();//[{key: 商店  ,value: v_2017...},{}]
    REPORT_CREATE.view.colDefs = new Array();
    REPORT_CREATE.newView = new Object();
    REPORT_CREATE.newView.name  = '';
    REPORT_CREATE.newView.template = new Object();
    REPORT_CREATE.newView.template.data = new Object();
    REPORT_CREATE.newView.template.value = 'default';
    REPORT_CREATE.newView.template.type = 'default';
    REPORT_CREATE.newView.queryIds = new Array();
    REPORT_CREATE.newView.queryHtml = new Array();
    REPORT_CREATE.newView.showTables = new Array();
    REPORT_CREATE.newView.grid = new Object();
    REPORT_CREATE.newView.grid.columnDefs = new Array();
    REPORT_CREATE.newView.table = new Object();
    REPORT_CREATE.newView.table.data = new Array();
    REPORT_CREATE.SPLIT_FLAG = "__";
    function headerCellRendererFunc(params) {
        var eHeader = document.createElement('span');
        var eTitle = document.createTextNode( params.colDef.headerName );
        eHeader.appendChild(eTitle);
        eHeader.addEventListener('click', function() {
            var dft_value = params.colDef.headerName;
            if ("<input type=\"text\">" == this.innerHTML) {
                var oldhtml = dft_value;
            }
            else {
                var oldhtml = this.innerHTML;
            }
            //创建新的input元素
            var newobj = document.createElement('input');
            //为新增元素添加类型
            newobj.type = 'text';
            //为新增元素添加value值
            newobj.value = oldhtml;
            newobj.addEventListener("keypress",function(event){
                if(event.keyCode == "13")
                {
                    if ("" == this.value)
                    {
                        eHeader.innerHTML = dft_value;
                    }
                    else
                    {
                        eHeader.innerHTML = this.value == oldhtml ? oldhtml : this.value;
                    }
                    params.colDef.headerName  = eHeader.innerHTML;
                }
            }, true);
            //设置该标签的子节点为空
            this.innerHTML = '';
            //添加该标签的子节点，input对象
            this.appendChild(newobj);
            //设置选择文本的内容或设置光标位置（两个参数：start,end；start为开始位置，end为结束位置；如果开始位置和结束位置相同则就是光标位置）
            newobj.setSelectionRange(0, oldhtml.length);
            //设置获得光标
            newobj.focus();
        });
        console.log(eHeader);
        return eHeader;
    }
    REPORT_CREATE.newView.grid.options =  {
        columnDefs             : REPORT_CREATE.newView.grid.columnDefs,
        rowData                : [],
        datasource             : null,
        rowHeight              : 40,
        colWidth               : 100,
        api                    : {},
        columnApi              : {},
        rowSelection           : 'single',
        showToolPanel: true,
        suppressColumnVirtualisation:true,
        toolPanelSuppressPivotMode:true,
        toolPanelSuppressRowGroups:true,
        toolPanelSuppressValues: true,
        headerCellRenderer: headerCellRendererFunc

    };

    REPORT_CREATE.showView = new Object();
    REPORT_CREATE.showView.template = new Object();

    REPORT_CREATE.showView.showColumns = new Array();
    REPORT_CREATE.showView.grid = new Object();
    REPORT_CREATE.showView.grid.options ={
        columnDefs             : [],
        rowData                : [],
        enableSorting: true,
        rowHeight: 40,
        colWidth: 100,
        suppressColumnVirtualisation:true,
        toolPanelSuppressPivotMode:true,
        toolPanelSuppressRowGroups:true,
        toolPanelSuppressValues: true
    };
    REPORT_CREATE.showView.grid.columnDefs = new Array();
    REPORT_CREATE.showView.grid.isHasGroup = new Object();
    REPORT_CREATE.showView.grid.isHasShowSubGroup = new Object();
    REPORT_CREATE.showView.grid.newExpCol = new Object();
    REPORT_CREATE.showView.grid.expCols = new Array();
    REPORT_CREATE.showView.queryIds = new Array();
    REPORT_CREATE.showView.queryHtml = new Array();
    REPORT_CREATE.showView.showTables = new Array();
    REPORT_CREATE.showView.vidForShowTables = new Object();
    REPORT_CREATE.autoIdOffset = 0;

    REPORT_CREATE.endView = new Object();
    REPORT_CREATE.endView.expressColumns = new Array();//[{key:, expressions:, , members:[,,]]
    REPORT_CREATE.endView.templateColumns = new Array();
    REPORT_CREATE.endView.showColumns = new Array();
    REPORT_CREATE.endView.grid = new Object();
    REPORT_CREATE.endView.grid.columnDefs = new Array();
    REPORT_CREATE.endView.grid.options ={
        columnDefs             : [],
        rowData                : [],
        enableSorting: true,
        rowHeight: 40,
        colWidth: 100,
        suppressColumnVirtualisation:true,
        toolPanelSuppressPivotMode:true,
        toolPanelSuppressRowGroups:true,
        toolPanelSuppressValues: true
    };
    REPORT_CREATE.EXPRESS_OFFSET =0;
    function getColNameFromStr(str)
    {
        var arr = str.split(REPORT_CREATE.SPLIT_FLAG); //字符分割
        if (arr.length >= 2)
        {
            return arr[0];
        }
        return null;
    }
    function getTableNameFromStr(str)
    {
        var arr = str.split(REPORT_CREATE.SPLIT_FLAG); //字符分割
        if (arr.length >=2)
        {
            return arr[1];
        }
        return null;
    }
    function getAutoGenerateVID()
    {
        REPORT_CREATE.autoIdOffset++;
        var id =0;
        for (var i =0; i < REPORT_CREATE.view.data.length; i++)
        {
            if (REPORT_CREATE.view.data[i]["auto_id"] >id)
            {
                id = REPORT_CREATE.view.data[i]["auto_id"];
            }
        }
        console.log("autoid:"+id);
        return ("v"+ (id + REPORT_CREATE.autoIdOffset).toString());
    }
    function refreshExpDisplay(){
        var exp = $("#inp_exp").children(".exp");
        var showExp ="";
        var expValue = "";
        var membersArr = new Array();
        for (var i=0; i< exp.length;i ++) {
            showExp+=exp[i].innerText;
        }
        $("#expSpanRet").html(showExp);
    }
    function isVerifyViewOptionsOK(){
        if ('default' == REPORT_CREATE.newView.template.type)
        {
            alert('请先选择视图或者数据表');
            return false;
        }
        if ('view' == REPORT_CREATE.newView.template.type && 'default' ==  $(".create_show_select_views").val())
        {
            alert('请选择某个视图');
            return false;
        }
        if ('data_table' == REPORT_CREATE.newView.template.type && 'default' ==  $(".create_show_select_tables").val())
        {
            alert('请选择某个数据表');
            return false;
        }
        return true;
    }


    function delDiv(obj) {
        console.log(obj);
        console.log(obj.id);
        var delId = "#"+ obj.id;
        $(delId).remove();
    }
    function delSpan(obj) {
        console.log(obj);
        var spanId = "#"+ obj;
        $(spanId).remove();
        refreshExpDisplay()
    }
    REPORT_CREATE.refreshData = function (){
        $(".create_show_select_views").empty();
        $(".create_show_select_views").append("<option value='default'>---请选择---</option>");
        $.get( REPORT_VIEW.baseUrl +"view/list", function(data) {
            REPORT_CREATE.view.data = data;
            console.log(data);
            for (var i =0; i < data.length; i++)
            {
                if (null == data[i]["view_name"])
                {
                    continue;
                }
                $(".create_show_select_views").append("<option value='"+data[i]["vid"]+"'>"+data[i]["view_name"]+"</option>");
            }
        });

        $.get( REPORT_VIEW.baseUrl +"express/list", function(data) {
            REPORT_CREATE.expressColumns.data = data;
            console.log("REPORT.expressColumns :"+ REPORT_CREATE.expressColumns.data );
        });

        $.get( REPORT_VIEW.baseUrl +"table/list", function(data) {
            $(".create_show_select_tables").empty();
            $(".create_show_select_tables").append("<option value='default'>---请选择---</option>");
            REPORT_CREATE.table.data = data.map(function (ele){
                $(".create_show_select_tables").append("<option value='"+ ele["key"]+"'>"+ ele["key"]+"</option>");
                return ele;
            });
        });
    };
    REPORT_CREATE.hide = function(){
        $('.js_create_show').find('.div-step').hide();
    };
     REPORT_CREATE.refreshData();
     $(".create_show_select_templates").val('default');
     $(".create_show_select_tables").val('default');
     $(".create_show_select_views").val('default');

     $('.js_create_show').find('.div-step').hide();

     $('.create_show_step_1').show();
     $(".create_show_select_tables").hide();
     $(".create_show_select_views").hide();

    var newGridDiv = document.querySelector('.create_show_new_grid');
    var showGridDiv = document.querySelector('.create_show_show_grid');
    var endGridDiv = document.querySelector('.create_show_end_grid');
    new agGrid.Grid(newGridDiv,  REPORT_CREATE.newView.grid.options);
    new agGrid.Grid(showGridDiv, REPORT_CREATE.showView.grid.options);
    new agGrid.Grid(endGridDiv,  REPORT_CREATE.endView.grid.options);

    $(".create_show_select_templates").change(function(){
        if ($(".create_show_select_templates").val() == 'view')
        {
            $(".create_show_select_tables").hide();
            $(".create_show_select_views").show();
            REPORT_CREATE.newView.template.type  = 'view';
        }
        else if ($(".create_show_select_templates").val() == 'data_table')
        {
            $(".create_show_select_tables").show();
            $(".create_show_select_views").hide();
            REPORT_CREATE.newView.template.type  = 'data_table';
        }
        else{
            $(".create_show_select_tables").hide();
            $(".create_show_select_views").hide();
            REPORT_CREATE.newView.template.value = 'default';
            REPORT_CREATE.newView.template.type = 'default';
        }
    });

    $(".create_show_step_1_next").click(function () {
        if (!isVerifyViewOptionsOK())
        {
            return;
        }
        REPORT_CREATE.view.colDefs = [];
        REPORT_CREATE.view.data.map (function (ele){
            if (ele["is_single_group"] == 'yes') {
                var colObjArr = JSON.parse(ele["cols_of_sub_groups"]);
                var curChildCols = new Array();
                for (var i =0; i <colObjArr.length; i++)
                {
                    if (colObjArr[i].hasOwnProperty("children"))
                    {
                        var subColObjArr =  colObjArr[i]["children"];
                        console.log(subColObjArr);
                        for (var j =0; j <subColObjArr.length; j++)
                        {
                            subColObjArr[j]['hide'] = true;
                            console.log(subColObjArr[j]);
                            curChildCols.push(subColObjArr[j]);
                        }
                    }
                    else
                    {
                        colObjArr[i]['hide'] = true;
                        curChildCols.push(colObjArr[i]);
                    }
                }
                REPORT_CREATE.view.colDefs.push({
                    headerName: ele["view_name"],
                    openByDefault: false,
                    children: curChildCols
                });
            }

        });
        REPORT_CREATE.expressColumns.colDefs = [];
        var expressGroupArr =[];
        var expressColArr =[];
        REPORT_CREATE.expressColumns.data.map(function (ele){
            if (ele["is_has_exp_group"] =='y')
            {
                expressColArr =[];
                REPORT_CREATE.expressColumns.data.map(function (subEle){
                    if (ele["group_name"] == subEle["group_name"]){
                        expressColArr.push(subEle);
                    }
                });
                expressGroupArr.push(expressColArr);
            }
        });
        for (var i =0; i < expressGroupArr.length; i ++)
        {
            var expressGroupName = "";
            var curExpCols =[];
            for (var j =0; j < expressGroupArr[i].length; j ++)
            {
                expressGroupName = expressGroupArr[i][j]["group_name"];
                curExpCols.push({
                    headerName:expressGroupArr[i][j]["header_name"],
                    field:expressGroupArr[i][j]["vid"],
                    valueGetter:expressGroupArr[i][j]["expressions"],
                    hide: true
                });
            }
            REPORT_CREATE.expressColumns.colDefs.push({
                headerName: expressGroupName,
                openByDefault: false,
                children: curExpCols
            });
        }

        REPORT_CREATE.table.colDefs  =  REPORT_CREATE.table.data.map(function (ele){
            return  {
                headerName   : ele["key"],
                openByDefault: false,
                children: ele["value"].map(function (sub_ele){
                    return {
                        headerName : sub_ele["key"],
                        field: sub_ele["key"] + REPORT_CREATE.SPLIT_FLAG + ele["key"],
                        hide: true,
                        filterParams : {newRowsAction: 'keep'}
                    };
                })
            };
        });
        console.log("table end ");
        if ('data_table' == REPORT_CREATE.newView.template.type)
        {
            REPORT_CREATE.newView.template.value = $(".create_show_select_tables").val();
            REPORT_CREATE.newView.template.data = null;
            REPORT_CREATE.newView.queryIds = [];
            REPORT_CREATE.newView.queryHtml ='';
            REPORT_CREATE.newView.showTables =[];
            REPORT_CREATE.newView.grid.columnDefs = [];
            Array.prototype.push.apply(REPORT_CREATE.newView.grid.columnDefs, REPORT_CREATE.view.colDefs);
            Array.prototype.push.apply(REPORT_CREATE.newView.grid.columnDefs, REPORT_CREATE.table.colDefs);
            REPORT_CREATE.newView.grid.options.api.setColumnDefs(REPORT_CREATE.newView.grid.columnDefs);
            REPORT_CREATE.newView.grid.options.api.softRefreshView();
            console.log(REPORT_CREATE.newView.grid.columnDefs);
            var showColumns = [];
            REPORT_CREATE.table.data.map(function (ele){
                if (ele["key"] == REPORT_CREATE.newView.template.value)
                {
                    ele["value"].map(function (sub_ele){
                        showColumns.push(sub_ele["key"] + REPORT_CREATE.SPLIT_FLAG + ele["key"]);
                    });
                }
            });
            REPORT_CREATE.newView.grid.options.columnApi.setColumnsVisible(showColumns, true);

        }
        else if ('view' == REPORT_CREATE.newView.template.type)
        {
            REPORT_CREATE.newView.template.value = $(".create_show_select_views").val();
            REPORT_CREATE.newView.template.data = null;
            console.log(REPORT_CREATE.newView.template.value);
            REPORT_CREATE.view.data.map(function (ele){
                if (REPORT_CREATE.newView.template.value == ele["vid"])
                {
                    REPORT_CREATE.newView.template.data = ele;
                    console.log(ele);
                }
            });
            if (null == REPORT_CREATE.newView.template.data)
            {
                alert("empty data");
                return
            }
            if ('' != REPORT_CREATE.newView.template.data["query_ids"])
            {
                REPORT_CREATE.newView.queryIds = JSON.parse(REPORT_CREATE.newView.template.data["query_ids"]);
            }
            REPORT_CREATE.newView.queryHtml = REPORT_CREATE.newView.template.data["query_html"];
            if ('' != REPORT_CREATE.newView.template.data["show_tables"])
            {
                REPORT_CREATE.newView.showTables = JSON.parse(REPORT_CREATE.newView.template.data["show_tables"]);
            }
            REPORT_CREATE.newView.grid.columnDefs =[];
            Array.prototype.push.apply(REPORT_CREATE.newView.grid.columnDefs, REPORT_CREATE.view.colDefs);
            Array.prototype.push.apply(REPORT_CREATE.newView.grid.columnDefs, REPORT_CREATE.expressColumns.colDefs);
            Array.prototype.push.apply(REPORT_CREATE.newView.grid.columnDefs, REPORT_CREATE.table.colDefs);
            console.log(REPORT_CREATE.newView.grid.columnDefs);
            REPORT_CREATE.newView.grid.options.api.setColumnDefs(REPORT_CREATE.newView.grid.columnDefs);
            REPORT_CREATE.newView.grid.options.api.softRefreshView();
            REPORT_CREATE.newView.grid.options.columnApi.setColumnsVisible(JSON.parse(REPORT_CREATE.newView.template.data["template_columns"]), true);
        }
        else
        {
            alert("请选择模版");
            return;
        }
        REPORT_CREATE.hide();
        $('.create_show_step_2').show();
    });
    $(".create_show_step_2_next").click(function () {
        /* refresh show tables from view template */
        var isValid = true;
        var viewGroups = [];
        if ('view' == REPORT_CREATE.newView.template.type)
        {
            console.log(REPORT_CREATE.newView.template.data);
            REPORT_CREATE.newView.showTables = JSON.parse(REPORT_CREATE.newView.template.data["show_tables"]);
            viewGroups = JSON.parse(REPORT_CREATE.newView.template.data["show_tables"]);
        }
        else
        {
            REPORT_CREATE.newView.showTables =[];
        }
        /* check all tables relations ; if no relation ,stop goto third step */
        console.log(REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumnGroups());
        var curShowTables = REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumnGroups();
        curShowTables = curShowTables.map(function (element){
            return element.getColGroupDef().headerName;
        });
        curShowTables.map(function (ele) {
            var pri_ele = ele;
            console.log (ele);
            console.log(REPORT_CREATE.newView.showTables);
            if (REPORT_CREATE.newView.showTables == [] || REPORT_CREATE.newView.showTables.indexOf(ele) < 0)
            {
                var subTableValue = "";
                if (ele.indexOf('t_') ==0)
                {
                    subTableValue = ele;
                }
                else{
                    //获取viewid
                    REPORT_CREATE.view.data.map(function (sub_ele){
                        if (ele == sub_ele["view_name"])
                        {
                            subTableValue = sub_ele["vid"];
                        }
                    });
                }
                if (REPORT_CREATE.newView.template.value === subTableValue || subTableValue == "")
                {
                    //todo 考虑 express 算法依赖
                    // 等于当前模版， 或者不是视图以及表（是express组，不用关系表）
                    return;
                }
                //是view模版的子表
                for (var i =0; i < viewGroups.length; i++)
                {
                    if (viewGroups[i] == subTableValue)
                    {
                        return;
                    }
                }

                $.ajax({
                    type : "get",
                    url : REPORT_VIEW.baseUrl + "table/"+REPORT_CREATE.newView.template.value+"/"+subTableValue+"/isRelated",
                    data : {},
                    async : false,
                    success : function(data){
                        if ('ok' != data)
                        {
                            isValid = false;
                            alert(data);
                            console.log("check:"+REPORT_CREATE.newView.template.value +REPORT_CREATE.SPLIT_FLAG+ele+":"+subTableValue);
                        }
                    }
                });

            }
        });

        if (!isValid)
        {
            return;
        }

        $('.make_show_search_content').html(REPORT_CREATE.newView.queryHtml);
        $('#create_show_multi_col_opts_id').hide();

        var view_third_step_sub_id_0_is_show = false;
        var colsForShowArr = REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumns();
        if (colsForShowArr.length >0)
        {
            $('.create_show_select_cols').empty();
            $('.create_show_select_cols').append("<option value='default'>---请选择---</option>");
        }
        colsForShowArr.map(function (ele){
            $('.create_show_select_cols').append("<option value='"
                + ele.getColId() +"'>"
                + ele.getColDef()["headerName"]
                + "</option>");
        });

        $('.create_show_select_cols').change(function(e){
            $('.create_show_select_range_opts').val('default');
            if (view_third_step_sub_id_0_is_show)
            {
                $("#create_show_multi_col_opts_id").pqSelect("destroy");
                $("#create_show_multi_col_opts_id").empty();
                $("#create_show_multi_col_opts_id").hide();
                view_third_step_sub_id_0_is_show = false;
            }
        });

        $('.create_show_select_range_opts').change(function(e){
            if ($('.create_show_select_cols').val() == "default")
            {
                $('.create_show_select_range_opts').val('default');
                alert("请先选择列名!");
            }
            else
            {
                if (view_third_step_sub_id_0_is_show)
                {
                    $("#create_show_multi_col_opts_id").pqSelect("destroy");
                    $("#create_show_multi_col_opts_id").empty();
                    $("#create_show_multi_col_opts_id").hide();
                    view_third_step_sub_id_0_is_show = false;
                }

                if (this.value == 'in')
                {
                    var coloumn_name = getColNameFromStr($('.create_show_select_cols').val());
                    var table_name   = getTableNameFromStr($('.create_show_select_cols').val());
                    $.get( REPORT_VIEW.baseUrl +"table/"+table_name+"/coloumn/"+coloumn_name+"/distinct",function(data) {
                        console.log(data);
                        for (var i =0; i < data.length; i++)
                        {
                            if (null == data[i][coloumn_name])
                            {
                                continue;
                            }
                            $("#create_show_multi_col_opts_id").append("<option value='"+data[i][coloumn_name]+"'>"+data[i][coloumn_name]+"</option>");
                        }

                        $("#create_show_multi_col_opts_id").pqSelect({
                            multiplePlaceholder: 'Select Regions',
                            checkbox: true //adds checkbox to options
                        }).on("change", function(evt) {
                            var val = $(this).val();
                        }).pqSelect('close');
                        view_third_step_sub_id_0_is_show = true;
                    });
                }

            }
        });
        REPORT_CREATE.hide();
        $('.create_show_step_3').show();
    });
    $(".create_show_step_3_next").click(function () {
        REPORT_CREATE.hide();
        REPORT_CREATE.newView.queryHtml = $('.make_show_search_content').html();

        $('.create_show_step_4').show();
        $('.parm1').show();
        $('.parm2').show();
        $('.parm3').hide();
        $('.parm4').hide();
    });
    $(".create_show_select_display_group").change(function(){
        if ('yes' == $(".create_show_select_display_group").val())
        {
            var curShowTables = REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumnGroups();
            if (curShowTables.length >=1)
            {
                $('.parm3').show();
            }
            $('.parm4').hide();
        }
        else if ('no' == $(".create_show_select_display_group").val())
        {
            $(".parm4").empty();
            $('.parm3').hide();
            $('.parm4').hide();
        }
        else{
            $(".create_show_select_show_subgroup").val('default');
            $(".parm4").empty();
            $('.parm3').hide();
            $('.parm4').hide();
        }
    });
    $(".create_show_select_show_subgroup").change(function(){
        REPORT_CREATE.newView.table.data =[];
        if ('yes' == $(".create_show_select_show_subgroup").val())
        {
            $('.parm4').show();
            var curShowTables = REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumnGroups();
            curShowTables = curShowTables.map(function (element){
                return element.getColGroupDef().headerName;
            });
            curShowTables.map(function(ele){
                if (ele.indexOf('t_') ==0)
                {
                    REPORT_CREATE.newView.table.data.push(ele);
                    $('.parm4').append("<div><span>"+ele+"</span><input type='text' id ='"+'txt'+ele+"' ></div>");
                }
            });
        }
        else if ('no' == $(".create_show_select_show_subgroup").val())
        {
            REPORT_CREATE.newView.table.data=[];
            $(".parm4").empty();
            $('.parm4').hide();
        }
        else{
            REPORT_CREATE.newView.table.data=[];
            $(".parm4").empty();
            $('.parm4').hide();
        }
    });
    $(".create_show_step_4_next").click(function () {
        REPORT_CREATE.showView.name = $("#view-new-name-id").val();
        var isDisplayGroup = $(".create_show_select_display_group").val();
        var isDisplaySubGroup = $(".create_show_select_show_subgroup").val();
        if ('' == REPORT_CREATE.showView.name)
        {
            alert("模版名称不能为空");
            return;
        }
        if (REPORT_CREATE.newView.name.indexOf("t_") == 0)
        {
            alert("模版名称不能以't_'开头");
            return;
        }
        //检测数据库是否存在名称
        //....
        if (isDisplayGroup == 'default')
        {
            alert("请选择是否显示组名");
            return;
        }

        if (isDisplayGroup == 'yes' && isDisplaySubGroup =='default')
        {
            alert("请选择是否显示子组");
            return;
        }

        if (REPORT_CREATE.newView.table.data.length > 0)
        {
            REPORT_CREATE.newView.table.name = new Array();
            for (var i =0; i <REPORT_CREATE.newView.table.data.length ; i ++)
            {
                var txtId ='#txt'+ REPORT_CREATE.newView.table.data[i];
                REPORT_CREATE.newView.table.name[i] = $(txtId).val();
            }
        }

        REPORT_CREATE.showView.vid = getAutoGenerateVID();
        console.log("vid====="+REPORT_CREATE.showView.vid);
        REPORT_CREATE.showView.queryIds = REPORT_CREATE.newView.queryIds;

        //清楚删除按钮，情况上一步查询条件div内容
        $(".make_show_search_query_opts").remove();
        REPORT_CREATE.showView.queryHtml = $('.make_show_search_content').html();
        $(".make_show_search_content").html("");

        REPORT_CREATE.showView.template = REPORT_CREATE.newView.template;
        REPORT_CREATE.showView.showTables =[];
        REPORT_CREATE.showView.vidForShowTables = new Object();
        var curShowGroups = REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumnGroups();
        var curShowTables = curShowGroups.map(function (element){
            return element.getColGroupDef().headerName;
        });
        curShowTables.map(function(ele){
            if (ele.indexOf('t_') == 0)
            {
                REPORT_CREATE.showView.showTables.push(ele);
            }
            else{
                console.log(REPORT_CREATE.showView.showTables);
                //考虑---- 视图为模版，属于模版子视图，不加入
                var templateViewArr= [];
                if ('view' == REPORT_CREATE.newView.template.type)
                {
                    templateViewArr = JSON.parse(REPORT_CREATE.newView.template.data["show_tables"]);
                }
                console.log("templateViewArr:"+templateViewArr);
                REPORT_CREATE.view.data.map (function (sub_ele){
                    if (sub_ele["view_name"] == ele) {
                        for (var j =0; j < templateViewArr.length ; j++)
                        {
                            if (sub_ele["vid"]== templateViewArr[j] ) {
                                if (REPORT_CREATE.showView.showTables.indexOf(REPORT_CREATE.newView.template.value) < 0) {
                                    REPORT_CREATE.showView.showTables.push(REPORT_CREATE.newView.template.value);
                                }
                                return;
                            }
                        }
                        console.log("templateViewArr:"+sub_ele["vid"]);
                        REPORT_CREATE.showView.showTables.push(sub_ele["vid"]);
                    }
                });
            }
        });
        console.log(REPORT_CREATE.showView.showTables);
        console.log(REPORT_CREATE.showView.vidForShowTables);

        REPORT_CREATE.showView.grid.columnDefs = [];
        REPORT_CREATE.showView.showColumns =[];
        REPORT_CREATE.showView.ColumnsForTemplate = new Object();
        var showViewGroupNum =0;
        if (isDisplayGroup == 'no')
        {
            REPORT_CREATE.showView.grid.isHasGroup = 'n';
            REPORT_CREATE.showView.grid.isHasShowSubGroup = 'n';
            REPORT_CREATE.showView.grid.columnDefs =  (REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumns()).map (function (ele) {
                var new_ele = ele.getColDef();
                if (new_ele["field"].indexOf("exp__") == 0)
                {
                    REPORT_CREATE.expressColumns.data.map(function (ele){
                        if (new_ele["field"] === ele["vid"]){
                            var newExpCol = new Object ();
                            newExpCol["vid"]="exp__"+ REPORT_CREATE.EXPRESS_OFFSET+"__"+REPORT_CREATE.showView.vid;
                            newExpCol["expressions"] = ele["expressions"];
                            var memberArr= JSON.parse(ele["members"]);
                            for (var i=0; i< memberArr.length;i ++) {
                                // 如果是表达式列，请替换成原成员
                                var member = "";
                                var oldStr = memberArr[i];
                                var arr = memberArr[i].split(REPORT_CREATE.SPLIT_FLAG); //字符分割
                                if (arr.length  >= 4)
                                {
                                    member = arr[0]+REPORT_CREATE.SPLIT_FLAG+arr[1]+REPORT_CREATE.SPLIT_FLAG+arr[2]+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                }
                                else
                                {
                                    member = str+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                }
                                newExpCol["expressions"]= newExpCol["expressions"].replace(oldStr, member);

                                console.log("newExpCol:"+newExpCol["expressions"]);
                                memberArr[i] = member;
                            }
                            newExpCol["members"] = JSON.stringify(memberArr);
                            newExpCol["header_name"]      = new_ele["headerName"];
                            newExpCol["is_has_exp_group"] = 'n';
                            newExpCol["group_name"] = '';
                            console.log ("exp:" +newExpCol);
                            REPORT_CREATE.EXPRESS_OFFSET++;
                            REPORT_CREATE.endView.expressColumns.push(newExpCol);//[{key:, expressions:, , members:[,,]]
                            new_ele["valueGetter"] = newExpCol["expressions"];
                        }
                    });
                }
                else
                {
                    var str = ele.getColId();
                    var arr = str.split(REPORT_CREATE.SPLIT_FLAG); //字符分割
                    if (arr.length  >= 4)
                    {
                        new_ele["field"] = arr[0]+REPORT_CREATE.SPLIT_FLAG+arr[1]+REPORT_CREATE.SPLIT_FLAG+arr[2]+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                    }
                    else
                    {
                        new_ele["field"] = str+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                    }
                }
                new_ele["hide"] = false;/*  修复 后面添加列 属性无法刷新 */
                REPORT_CREATE.showView.showColumns.push(new_ele["field"]);
                return (new_ele);
            });
            showViewGroupNum ++;
        }
        else{
            REPORT_CREATE.showView.grid.isHasGroup = 'y';
            if (isDisplaySubGroup == 'no')
            {
                REPORT_CREATE.showView.grid.isHasShowSubGroup = 'n';
                REPORT_CREATE.showView.grid.columnDefs.push ({
                    headerName: REPORT_CREATE.showView.name,
                    openByDefault: false,
                    children: (REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumns()).map (function (ele) {
                        var new_ele = ele.getColDef();
                        if (new_ele["field"].indexOf("exp__") == 0)
                        {
                            REPORT_CREATE.expressColumns.data.map(function (ele){
                                if (new_ele["field"] === ele["vid"]){
                                    var newExpCol = new Object ();
                                    newExpCol["vid"]="exp__"+ REPORT_CREATE.EXPRESS_OFFSET+"__"+REPORT_CREATE.showView.vid;
                                    newExpCol["expressions"] = ele["expressions"];
                                    var memberArr= JSON.parse(ele["members"]);
                                    for (var i=0; i< memberArr.length;i ++) {
                                        // 如果是表达式列，请替换成原成员
                                        var member = "";
                                        var oldStr = memberArr[i];
                                        var arr = memberArr[i].split(REPORT_CREATE.SPLIT_FLAG); //字符分割
                                        if (arr.length  >= 4)
                                        {
                                            member = arr[0]+REPORT_CREATE.SPLIT_FLAG+arr[1]+REPORT_CREATE.SPLIT_FLAG+arr[2]+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                        }
                                        else
                                        {
                                            member = str+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                        }
                                        newExpCol["expressions"]= newExpCol["expressions"].replace(oldStr, member);

                                        console.log("newExpCol:"+newExpCol["expressions"]);
                                        memberArr[i] = member;
                                    }
                                    newExpCol["members"] = JSON.stringify(memberArr);
                                    newExpCol["header_name"]      = new_ele["headerName"];
                                    newExpCol["is_has_exp_group"] = 'n';
                                    newExpCol["group_name"] = '';

                                    console.log ("exp:" +newExpCol);
                                    REPORT_CREATE.EXPRESS_OFFSET++;
                                    REPORT_CREATE.endView.expressColumns.push(newExpCol);//[{key:, expressions:, , members:[,,]]
                                    new_ele["valueGetter"] = newExpCol["expressions"];
                                }
                            });
                        }
                        else
                        {
                            var str = ele.getColId();
                            var arr = str.split(REPORT_CREATE.SPLIT_FLAG); //字符分割
                            if (arr.length  >= 4)
                            {
                                new_ele["field"] = arr[0]+REPORT_CREATE.SPLIT_FLAG+arr[1]+REPORT_CREATE.SPLIT_FLAG+arr[2]+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                            }
                            else
                            {
                                new_ele["field"] = str+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                            }
                        }
                        new_ele["hide"] = false;/*  修复 后面添加列 属性无法刷新 */
                        REPORT_CREATE.showView.showColumns.push(new_ele["field"]);
                        return (new_ele);
                    })
                });
                showViewGroupNum ++;
            }
            else{
                REPORT_CREATE.showView.grid.isHasShowSubGroup = 'y';
                curShowGroups.map(function (ele){
                    var isExpressGroup = true;
                    var groupName = ele.getColGroupDef().headerName;
                    var groupId ='';
                    if (groupName.indexOf('t_') ==0)
                    {
                        var txtId ='#txt'+ groupName;
                        console.log(groupName);
                        REPORT_CREATE.showView.vidForShowTables[groupName] = getAutoGenerateVID();
                        groupId = REPORT_CREATE.showView.vidForShowTables[groupName];
                        groupName = $(txtId).val();
                        console.log(groupId);
                        isExpressGroup = false;
                    }
                    else
                    {
                        REPORT_CREATE.view.data.map(function (sub_ele){
                            if (groupName == sub_ele["view_name"])
                            {
                                isExpressGroup = false;
                            }
                        });
                    }
                    REPORT_CREATE.showView.grid.columnDefs.push ({
                        headerName: groupName,
                        openByDefault: false,
                        children: (ele.children).map (function (ele) {
                            var new_ele = ele.getColDef();
                            if (new_ele["field"].indexOf("exp__") == 0)
                            {
                                REPORT_CREATE.expressColumns.data.map(function (ele){
                                    if (new_ele["field"] === ele["vid"]){
                                        var newExpCol = new Object ();
                                        newExpCol["vid"]="exp__"+ REPORT_CREATE.EXPRESS_OFFSET+"__"+REPORT_CREATE.showView.vid;
                                        newExpCol["expressions"] = ele["expressions"];
                                        var memberArr= JSON.parse(ele["members"]);
                                        for (var i=0; i< memberArr.length;i ++) {
                                            // 如果是表达式列，请替换成原成员
                                            var member = "";
                                            var oldStr = memberArr[i];
                                            var arr = memberArr[i].split(REPORT_CREATE.SPLIT_FLAG); //字符分割

                                            if (arr.length  >= 4)
                                            {
                                                member = arr[0] +REPORT_CREATE.SPLIT_FLAG+ arr[1]+REPORT_CREATE.SPLIT_FLAG+arr[2]+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                                REPORT_CREATE.showView.ColumnsForTemplate[member]  = str;
                                            }
                                            else if (arr.length  == 2) {
                                                member = str +REPORT_CREATE.SPLIT_FLAG+ groupId+ REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                                REPORT_CREATE.showView.ColumnsForTemplate[member]  = (str +REPORT_CREATE.SPLIT_FLAG+ groupId);
                                            }
                                            else{
                                                member = str +REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                                REPORT_CREATE.showView.ColumnsForTemplate[member] = str;
                                            }
                                            newExpCol["expressions"]= newExpCol["expressions"].replace(oldStr, member);

                                            console.log("newExpCol:"+newExpCol["expressions"]);
                                            memberArr[i] = member;
                                        }
                                        newExpCol["members"] = JSON.stringify(memberArr);
                                        newExpCol["header_name"]      = new_ele["headerName"];
                                        if (isExpressGroup){
                                            newExpCol["is_has_exp_group"] = 'y';
                                            newExpCol["group_name"] = groupName;
                                        }
                                        else{
                                            newExpCol["is_has_exp_group"] = 'n';
                                            newExpCol["group_name"] = '';
                                        }
                                        console.log ("exp:" +newExpCol);
                                        REPORT_CREATE.EXPRESS_OFFSET++;
                                        REPORT_CREATE.endView.expressColumns.push(newExpCol);//[{key:, expressions:, , members:[,,]]
                                        new_ele["valueGetter"] = newExpCol["expressions"];
                                    }
                                });
                            }
                            else
                            {
                                var str = ele.getColId();
                                var arr = str.split(REPORT_CREATE.SPLIT_FLAG); //字符分割
                                if (arr.length  >= 4)
                                {
                                    new_ele["field"] = arr[0] +REPORT_CREATE.SPLIT_FLAG+ arr[1]+REPORT_CREATE.SPLIT_FLAG+arr[2]+REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                    REPORT_CREATE.showView.ColumnsForTemplate[new_ele["field"]] = str;
                                }
                                else if (arr.length  == 2) {
                                    new_ele["field"] = str +REPORT_CREATE.SPLIT_FLAG+ groupId+ REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                    REPORT_CREATE.showView.ColumnsForTemplate[new_ele["field"]] =(str +REPORT_CREATE.SPLIT_FLAG+ groupId);
                                }
                                else{
                                    new_ele["field"] = str +REPORT_CREATE.SPLIT_FLAG+ REPORT_CREATE.showView.vid;
                                    REPORT_CREATE.showView.ColumnsForTemplate[new_ele["field"]] = str;
                                }
                            }

                            new_ele["hide"] = false;/*  修复 后面添加列 属性无法刷新 */
                            REPORT_CREATE.showView.showColumns.push(new_ele["field"]);
                            return (new_ele);
                        })
                    });

                    showViewGroupNum ++;

                });
            }
        }
        console.log("showViewGroupNum ="+showViewGroupNum);
        if (showViewGroupNum >1)
        {
            REPORT_CREATE.showView.grid.isSingleGroup = 'no';
        }
        else{
            REPORT_CREATE.showView.grid.isSingleGroup = 'yes';
        }
        console.log(REPORT_CREATE.showView.grid.columnDefs);
        REPORT_CREATE.showView.grid.options.api.setColumnDefs(REPORT_CREATE.showView.grid.columnDefs);
        REPORT_CREATE.showView.grid.options.api.softRefreshView();
        //--------------------  exp col -----------------
        $('#selEle').empty();
        // 显示子组，新增需要增加组名，其他只需要加列
        if (REPORT_CREATE.showView.grid.isHasGroup === 'y')
        {
            var cols = REPORT_CREATE.showView.grid.columnDefs;
            console.log("cols:"+ cols);
            for (var i =0; i < cols.length; i ++) {
                var colsOfGroup = cols[i]["children"];
                for (var j=0; j < colsOfGroup.length; j ++)
                {
                    $('#selEle').append("<option value='"+colsOfGroup[j]["field"]+"'>"+cols[i]["headerName"]+"."+colsOfGroup[j]["headerName"]+"</option>");
                }
            }
            if (REPORT_CREATE.showView.grid.isHasShowSubGroup === 'n'){
                $('#divNewExpColSubGroup').hide();
            }
        }
        else
        {
            $('#divNewExpColSubGroup').hide();
            var cols = REPORT_CREATE.showView.grid.columnDefs;
            console.log("cols:"+ cols);
            for (var i =0; i < cols.length; i ++) {
                $('#selEle').append("<option value='"+cols[i]["field"]+"'>"+cols[i]["headerName"]+"</option>");
            }
        }

        REPORT_CREATE.hide();
        $(".create_show_show_query_options").html(REPORT_CREATE.showView.queryHtml);
        $('.create_show_step_5').show();
        $('.view_parms').hide();
        console.log("step 5");
    });
    $(".create_show_step_5_next").click(function () {
        $(".create_show_end_query_options").html("");
        $(".create_show_end_query_options").html(REPORT_CREATE.showView.queryHtml);
        REPORT_CREATE.endView.showColumns =[];
        REPORT_CREATE.endView.templateColumns =[];
        REPORT_CREATE.endView.grid.columnDefs =[];
        if (REPORT_CREATE.showView.grid.isHasGroup === 'n') {
            REPORT_CREATE.endView.grid.columnDefs =  (REPORT_CREATE.showView.grid.options.columnApi.getAllDisplayedColumns()).map (function (ele) {
                var new_ele = ele.getColDef();
                new_ele["hide"] = false;
                /*  修复 后面添加列 属性无法刷新 */
                if (new_ele["field"].indexOf("exp__") != 0) {
                    REPORT_CREATE.endView.showColumns.push(new_ele["field"]);
                }
                REPORT_CREATE.endView.templateColumns.push(new_ele["field"]);
                return (new_ele);
            });
        }
        else{
            if (REPORT_CREATE.showView.grid.isHasShowSubGroup === 'n')
            {
                REPORT_CREATE.endView.grid.columnDefs.push ({
                    headerName: REPORT_CREATE.showView.name,
                    openByDefault: false,
                    children: (REPORT_CREATE.showView.grid.options.columnApi.getAllDisplayedColumns()).map (function (ele) {
                        var new_ele = ele.getColDef();
                        new_ele["hide"] = false;/*  修复 后面添加列 属性无法刷新 */
                        if (new_ele["field"].indexOf("exp__") != 0) {
                            REPORT_CREATE.endView.showColumns.push(new_ele["field"]);
                        }
                        REPORT_CREATE.endView.templateColumns.push(new_ele["field"]);
                        return (new_ele);
                    })
                });
            }
            else
            {
                var curShowGroups = REPORT_CREATE.showView.grid.options.columnApi.getAllDisplayedColumnGroups();
                var curShowTables = curShowGroups.map(function (element){
                    return element.getColGroupDef().headerName;
                });
                curShowGroups.map(function (ele){
                    REPORT_CREATE.endView.grid.columnDefs.push ({
                        headerName: ele.getColGroupDef().headerName,
                        openByDefault: false,
                        children: (ele.children).map (function (ele) {
                            var new_ele = ele.getColDef();
                            new_ele["hide"] = false;/*  修复 后面添加列 属性无法刷新 */
                            if (new_ele["field"].indexOf("exp__") != 0) {
                                REPORT_CREATE.endView.showColumns.push(new_ele["field"]);
                            }
                            if (REPORT_CREATE.showView.ColumnsForTemplate.hasOwnProperty(new_ele["field"]) )
                            {
                                REPORT_CREATE.endView.templateColumns.push(REPORT_CREATE.showView.ColumnsForTemplate[new_ele["field"]]);
                            }
                            else
                            {
                                REPORT_CREATE.endView.templateColumns.push(new_ele["field"]);
                            }
                            return (new_ele);
                        })
                    });
                });
            }

        }

        REPORT_CREATE.endView.grid.options.api.setColumnDefs(REPORT_CREATE.endView.grid.columnDefs);
        REPORT_CREATE.endView.grid.options.api.softRefreshView();

        REPORT_CREATE.hide();
        $(".create_show_show_query_options").html("");
        $('.create_show_step_6').show();
        $('.view_parms').hide();
        console.log("step 6");
    });
    $(".create_show_end_excel").click(function() {
        REPORT_CREATE.endView.grid.options.api.exportDataAsExcel({
            skipHeader: false,
            columnGroups: false,
            skipFooters: false,
            skipGroups: false,
            skipFloatingTop: false,
            skipFloatingBottom: false,
            allColumns: false,
            onlySelected: false,
            fileName: $("#inpExcelFileName").val()
        });
    });
    $(".create_show_end_search").click(function() {
        var queryOpt =  new Array();
        var queryAllObj = REPORT_CREATE.showView.queryIds;
        console.log(REPORT_CREATE.showView.queryIds);
        console.log(queryAllObj);
        for (var i =0; i < queryAllObj.length; i++)
        {
            var query_id = "#" +  queryAllObj[i]["key"];
            var query_sub_opt_value = queryAllObj[i]["value"];
            var queryOptValue = new Array();

            console.log (query_id);
            if (null == $(query_id).val() || '' == $(query_id).val() || 'default' == $(query_id).val())
            {
                queryOpt.push(queryAllObj[i]);

            }
            else
            {
                queryOptValue.push($(query_id).val());
                queryOpt.push({"key" :queryAllObj[i]["key"], "value":{"key": query_sub_opt_value["key"], "value": queryOptValue} });
            }

        }
        var showViewData = new Object();
        showViewData["vid"] = REPORT_CREATE.showView.vid;
        showViewData["template_name"] = REPORT_CREATE.showView.template["value"];
        showViewData["show_tables"] =  JSON.stringify(REPORT_CREATE.showView.showTables); //关系表在showView之后不在变化
        showViewData["show_columns"] = JSON.stringify(REPORT_CREATE.endView.showColumns); // 显示数据变化
        showViewData["query_ids"] =  JSON.stringify(queryOpt);
        var  tablesForCreateArr = [];
        REPORT_CREATE.showView.showTables.map(function (ele){
            if(ele.indexOf("t_") ==0 && REPORT_CREATE.showView.grid.isHasShowSubGroup == 'y')
            {
                tablesForCreateArr.push(ele);
            }
        });
        if (tablesForCreateArr.length ==0)
        {
            showViewData["table_of_view"]="";
        }
        else
        {
            var viewsForTable = [];
            for (var i =0; i < tablesForCreateArr.length; i++)
            {
                viewsForTable.push({ key: tablesForCreateArr[i],
                    value:REPORT_CREATE.showView.vidForShowTables[tablesForCreateArr[i]]
                });
            }
            showViewData["table_of_view"]= JSON.stringify(viewsForTable);
        }

        console.log(showViewData);
        $.get( REPORT_VIEW.baseUrl +"view/template",{data: JSON.stringify(showViewData)} ,function(data){
            console.log(data);
            REPORT_CREATE.endView.grid.options.api.setRowData(data);
        });
    });
    $(".create_show_show_search").click(function() {
        var queryOpt =  new Array();
        var queryAllObj = REPORT_CREATE.showView.queryIds;
        console.log(REPORT_CREATE.showView.queryIds);
        console.log(queryAllObj);
        for (var i =0; i < queryAllObj.length; i++)
        {
            var query_id = "#" +  queryAllObj[i]["key"];
            var query_sub_opt_value = queryAllObj[i]["value"];
            var queryOptValue = new Array();
            console.log (query_id);
            if (null == $(query_id).val() || '' == $(query_id).val() || 'default' == $(query_id).val())
            {
                queryOpt.push(queryAllObj[i]);

            }
            else
            {
                queryOptValue.push($(query_id).val());
                queryOpt.push({"key" :queryAllObj[i]["key"], "value":{"key": query_sub_opt_value["key"], "value": queryOptValue} });
            }

        }
        var showViewData = new Object();
        showViewData["vid"] = REPORT_CREATE.showView.vid;
        showViewData["template_name"] = REPORT_CREATE.showView.template["value"];
        showViewData["show_tables"] =  JSON.stringify(REPORT_CREATE.showView.showTables);
        showViewData["show_columns"] = JSON.stringify(REPORT_CREATE.showView.showColumns);
        showViewData["query_ids"] =  JSON.stringify(queryOpt);

        var  tablesForCreateArr = [];
        REPORT_CREATE.showView.showTables.map(function (ele){
            if(ele.indexOf("t_") ==0 && REPORT_CREATE.showView.grid.isHasShowSubGroup == 'y')
            {
                tablesForCreateArr.push(ele);
            }
        });
        if (tablesForCreateArr.length ==0)
        {
            showViewData["table_of_view"]="";
        }
        else
        {
            var viewsForTable = [];
            for (var i =0; i < tablesForCreateArr.length; i++)
            {
                viewsForTable.push({ key: tablesForCreateArr[i],
                    value:REPORT_CREATE.showView.vidForShowTables[tablesForCreateArr[i]]
                });
            }
            showViewData["table_of_view"]= JSON.stringify(viewsForTable);
        }

        console.log(showViewData);
        $.get( REPORT_VIEW.baseUrl +"view/template",{data: JSON.stringify(showViewData)} ,function(data){
            console.log(data);
            REPORT_CREATE.showView.grid.options.api.setRowData(data);
        });
    });
    $(".cancel").click(function () {
        $('.data-overlay').hide();
    });
    $(".save").click(function () {
        var info = "是否保存模版'"+ REPORT_CREATE.showView.name +"'[y/n]";
        var new_view_name = prompt(info);
        if (new_view_name !== 'y'){
            return;
        }
        if (!isVerifyViewOptionsOK())
        {
            return;
        }

        for (var i =0; i < REPORT_CREATE.showView.showTables.length; i++)
        {
            if (REPORT_CREATE.showView.showTables[i].indexOf('t_') == 0 && REPORT_CREATE.showView.grid.isHasShowSubGroup == 'y')
            {
                var singleViewData = new Object();
                console.log(REPORT_CREATE.showView.showTables[i]);
                singleViewData ["vid"] = REPORT_CREATE.showView.vidForShowTables[REPORT_CREATE.showView.showTables[i]];
                var txtId ='#txt'+ REPORT_CREATE.showView.showTables[i];
                singleViewData ["template_name"] = REPORT_CREATE.showView.showTables[i];
                if ($(txtId).val() == "")
                {
                    continue;
                }
                singleViewData ["view_name"] = $(txtId).val();
                var singleViewShowTables = new Array();
                singleViewShowTables.push(REPORT_CREATE.showView.showTables[i]);
                singleViewData ["show_tables"] = JSON.stringify(singleViewShowTables);
                var singleViewShowCols = new Array();
                var singleViewColDefs = new Array();
                REPORT_CREATE.newView.grid.options.columnApi.getAllDisplayedColumnGroups().map(function (element){
                    var groupName = element.getColGroupDef().headerName;
                    if (groupName == REPORT_CREATE.showView.showTables[i])
                    {
                        singleViewColDefs.push ({
                            headerName: singleViewData ["view_name"],
                            openByDefault: false,
                            children: (element.children).map (function (sub_ele) {
                                var new_ele = sub_ele.getColDef();
                                var str = sub_ele.getColId();
                                new_ele["field"] = str+ REPORT_CREATE.SPLIT_FLAG+ singleViewData ["vid"];
                                new_ele["hide"] = false;/*  修复 后面添加列 属性无法刷新 */
                                singleViewShowCols.push(new_ele["field"]);
                                return (new_ele);
                            })
                        });
                    }

                });
                singleViewData["cols_of_sub_groups"] = singleViewColDefs;
                singleViewData["is_single_group"] = 'yes';
                singleViewData["show_columns"]  = JSON.stringify(singleViewShowCols);
                singleViewData["template_columns"]  = JSON.stringify(singleViewShowCols);
                singleViewData["query_ids"] =  '';
                singleViewData["query_html"] = '';
                singleViewData["grid_options"] = JSON.stringify({
                    columnDefs: singleViewColDefs,
                    rowData: null,
                    enableSorting: true,
                    rowGroupPanelShow: 'always'
                });
                console.log(singleViewData);
                $.ajax({
                    type : "post",
                    url  : REPORT_VIEW.baseUrl + "view/new",
                    data : {data: JSON.stringify(singleViewData)},
                    async : false,
                    success : function(data){
                        console.log(data);
                    }
                });
                if (REPORT_CREATE.showView.template["value"] == REPORT_CREATE.showView.showTables[i])
                {
                    REPORT_CREATE.showView.template["value"] = singleViewData ["vid"];
                }
                REPORT_CREATE.showView.showTables[i] = singleViewData ["vid"];

            }
        }

        console.log(REPORT_CREATE.endView.grid.options.columnApi.getAllGridColumns());
        var showViewData = new Object();
        showViewData["vid"] = REPORT_CREATE.showView.vid;
        showViewData["template_name"] = REPORT_CREATE.showView.template["value"];
        showViewData["view_name"]  = REPORT_CREATE.showView.name;
        showViewData["show_tables"] = JSON.stringify(REPORT_CREATE.showView.showTables);
        showViewData["query_ids"] =  JSON.stringify(REPORT_CREATE.showView.queryIds);

        REPORT_CREATE.endView.queryIds =[];
        REPORT_CREATE.endView.queryHtml = REPORT_CREATE.showView.queryHtml;
        REPORT_CREATE.showView.queryIds.map(function (ele){
            if (ele["key"].endsWith(showViewData["vid"]))
            {

                REPORT_CREATE.endView.queryIds.push(ele);
            }
            else{
                var oldKey = ele["key"];
                var newKey="";
                var keyEleArr = ele["key"].split(REPORT_CREATE.SPLIT_FLAG);
                if (keyEleArr.length  >= 4)
                {
                    newKey = keyEleArr[0] +REPORT_CREATE.SPLIT_FLAG+ keyEleArr[1]+REPORT_CREATE.SPLIT_FLAG+keyEleArr[2]+ REPORT_CREATE.SPLIT_FLAG + showViewData["vid"];
                }
                else {
                    newKey = oldKey + REPORT_CREATE.SPLIT_FLAG + showViewData["vid"];
                }
                REPORT_CREATE.endView.queryIds.push({key:newKey, value:ele["value"]});

                REPORT_CREATE.endView.queryHtml = REPORT_CREATE.endView.queryHtml.replace(new RegExp(oldKey, "gm"), newKey);
            }
        });
        //todo
        showViewData["new_query_ids"] =  JSON.stringify(REPORT_CREATE.endView.queryIds);
        showViewData["query_html"] = REPORT_CREATE.endView.queryHtml;

        showViewData["template_columns"]  = JSON.stringify(REPORT_CREATE.endView.templateColumns);
        showViewData["show_columns"]  = JSON.stringify(REPORT_CREATE.endView.showColumns);
        showViewData["cols_of_sub_groups"] = JSON.stringify(REPORT_CREATE.endView.grid.columnDefs);
        showViewData["grid_options"] = JSON.stringify({
            columnDefs: REPORT_CREATE.endView.grid.columnDefs,
            rowData: null,
            enableSorting: true,
            rowGroupPanelShow: 'always'
        });

        showViewData["is_single_group"] = REPORT_CREATE.showView.grid.isSingleGroup;
        var expressCols = "";
        if (REPORT_CREATE.endView.expressColumns.length !=0)
        {
            REPORT_CREATE.endView.expressColumns = REPORT_CREATE.endView.expressColumns;
            expressCols = JSON.stringify(REPORT_CREATE.endView.expressColumns);
        }
        console.log(JSON.stringify(showViewData));
        $.ajax({
            type: 'post',
            url:  REPORT_VIEW.baseUrl +"view/new",
            data: {data: JSON.stringify(showViewData),expressData :expressCols},
            success: function(result){
                alert(result);
                REPORT_CREATE.endView.expressColumns=[];
                $('.data-overlay').hide();
            },
            error:function(xhr,status,statusText){
                console.log(xhr);
                console.log(xhr.status);
                console.log(xhr.statusText);
                alert(xhr.responseText);
                return;
            }
            //dataType: 'text'
        });
    });

    var spanId =0;
    $("#addEle").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId +"'  value= 'data."+ $('#selEle').val() +"' class='exp'  >"
            + $('#selEle').find("option:selected").text() +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></span>");
        refreshExpDisplay();
    });
    $("#flagPlus").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId +"'  value= '+' class='exp'  >"
            + "+" +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></span>");
        refreshExpDisplay();
    });
    $("#flagReduce").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId  +"'  value= '-'  class='exp' >"
            + "-" +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></span>");
        refreshExpDisplay();
    });
    $("#flagMultil").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId +"'  value= '*'  class='exp' >"
            + "*" +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></span>");
        refreshExpDisplay();
    });
    $("#flagDivision").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId  +"'  value= '/'  class='exp' >"
            + "/" +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></span>");
        refreshExpDisplay();
    });
    $("#flagLeftBrackets").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId +"'  value= '('  class='exp' >"
            + "(" +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></span>");
        refreshExpDisplay();
    });
    $("#flagRightBrackets").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId  +"'  value= ')'  class='exp' >"
            + ")" +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></div>");
        refreshExpDisplay();
    });
    $("#addNum").click(function() {
        spanId++;
        $("#inp_exp").append("<span  id = '"+ spanId +"'  value= '"+  $('#inpNum').val()  +"'  class='exp' >"
            + $('#inpNum').val() +
            "<span class='fa fa-close' onclick='delSpan("+spanId+")'></span></span>");
        refreshExpDisplay();
    });
    $("#btt_geneteExpCol").click(function() {
        var exp = $("#inp_exp").children(".exp");
        if  (null == exp || exp.length ==0)
        {
            alert("公式不能为空")
            return ;
        }
        if ("" == $("#inpNewExpColSubCol").val())
        {
            alert("输入列名")
            return ;
        }
        if (REPORT_CREATE.showView.grid.isHasGroup === 'y' && REPORT_CREATE.showView.grid.isHasShowSubGroup === 'y' && "" ==$("#inpNewExpColSubGroup").val())
        {
            alert("输入组名")
            return ;
        }

        var newExpCol = new Object ();
        newExpCol["vid"]="exp__"+ REPORT_CREATE.EXPRESS_OFFSET+"__"+REPORT_CREATE.showView.vid;
        newExpCol["expressions"] = "";
        var memberArr= new Array();
        for (var i=0; i< exp.length;i ++) {
            newExpCol["expressions"]+= exp[i].getAttribute('value');
            //todo
            // 如果是表达式列，请替换成原成员
            if (exp[i].getAttribute('value').indexOf("data.") ==0)
            {
                memberArr.push(exp[i].getAttribute('value').replace("data.",""));
            }
        }
        if ("" != $("#inpNewExpColSubCol").val())
        {
            newExpCol["header_name"] = $("#inpNewExpColSubCol").val();
            newExpCol["is_has_exp_group"] = 'n';
            newExpCol["group_name"] = '';
        }
        if (REPORT_CREATE.showView.grid.isHasGroup === 'y' && REPORT_CREATE.showView.grid.isHasShowSubGroup === 'y')
        {
            newExpCol["is_has_exp_group"] = 'y';
            newExpCol["group_name"] = $("#inpNewExpColSubGroup").val() ;
        }

        newExpCol["members"] = JSON.stringify(memberArr);
        console.log ("exp:" +newExpCol);
        REPORT_CREATE.EXPRESS_OFFSET++;
        REPORT_CREATE.endView.expressColumns.push(newExpCol);//[{key:, expressions:, , members:[,,]]
        console.log("express"+REPORT_CREATE.endView.expressColumns);
        if (REPORT_CREATE.showView.grid.isHasGroup === 'y')
        {
            if (REPORT_CREATE.showView.grid.isHasShowSubGroup === 'y')
            {
                var expArr = [{
                    headerName:$("#inpNewExpColSubCol").val(),
                    field:newExpCol["vid"],
                    valueGetter:newExpCol["expressions"]
                }];
                //todo 如果存在组
                REPORT_CREATE.showView.grid.columnDefs.push({
                    headerName:$("#inpNewExpColSubGroup").val(),
                    openByDefault: false,
                    children:expArr
                });
                REPORT_CREATE.showView.grid.options.api.setColumnDefs(REPORT_CREATE.showView.grid.columnDefs);
                REPORT_CREATE.showView.grid.options.api.softRefreshView();
            }
            else{
                var  tmpCols = REPORT_CREATE.showView.grid.columnDefs[0];
                tmpCols["children"].push({
                    headerName:$("#inpNewExpColSubCol").val(),
                    field:newExpCol["vid"],
                    valueGetter:newExpCol["expressions"]
                });
                REPORT_CREATE.showView.grid.options.api.setColumnDefs(REPORT_CREATE.showView.grid.columnDefs);
                REPORT_CREATE.showView.grid.options.api.softRefreshView();
            }
        }
        else{
            REPORT_CREATE.showView.grid.columnDefs.push({
                headerName:$("#inpNewExpColSubCol").val(),
                field:newExpCol["vid"],
                valueGetter:newExpCol["expressions"]
            });
            REPORT_CREATE.showView.grid.options.api.setColumnDefs(REPORT_CREATE.showView.grid.columnDefs);
            REPORT_CREATE.showView.grid.options.api.softRefreshView();
        }


        $("#inpNewExpColSubCol").val("");
        $("#inpNewExpColSubGroup").val("");
        $("#expSpanRet").html("");
        $("#inp_exp").html("");
        $('.js_create_new_list_show').fadeOut();
    });
    $(".create_show_add_query_opt").click(function () {
        var queryOptId    = $('.create_show_select_cols').val();
        var spanId = "div" + $('.create_show_select_cols').val();
        var queryOptValue = new Object();
        if ($('.create_show_select_range_opts').val() == 'in')
        {
            var opts_arr = $("#create_show_multi_col_opts_id").val();
            if (null == opts_arr || opts_arr.length == 0)
            {
                alert ("请选择条件")
                return;
            }
            var opts_str    ="<option value='default' >---请选择---</option>";
            var optValueArr = new Array();
            for (var i =0 ; i< opts_arr.length; i++ )
            {
                opts_str += "<option value='"+opts_arr [i] +"'> "+ opts_arr [i]+"</option>"
                optValueArr[i] = opts_arr [i];
            }
            console.log("queryOptId="+ queryOptId);
            $('.make_show_search_content').append("<div  id = '"+ spanId +"'><span>"
                + $('.create_show_select_cols').find("option:selected").text()
                + ": </span>"+ "<select id='"
                + queryOptId
                +"' >"
                + opts_str
                +"</select> "
                +"<span class='fa fa-close make_show_search_query_opts' onclick='delDiv("+spanId+")'></span></div>");//<span class='fa fa-close'></span>

            queryOptValue ["key"] = "in";
            queryOptValue ["value"] = optValueArr;
        }
        REPORT_CREATE.newView.queryIds.push({
            key:queryOptId,
            value:queryOptValue
        });
        REPORT_CREATE.newView.queryHtml = $('.make_show_search_content').html();

    });

     // 添加新列
     $('.js_create_new_list').click(function(){
         $('.js_create_new_list_show').fadeIn();
     });

     $('.js_create_new_list_close').click(function(){
         $('.js_create_new_list_show').fadeOut();
     });

    $(".create_show_step_2_last").click(function () {
        REPORT_CREATE.hide();
        $('.create_show_step_1').show();
    });
    $(".create_show_step_3_last").click(function () {
        REPORT_CREATE.hide();
        $('.create_show_step_2').show();
    });
    $(".create_show_step_4_last").click(function () {
        $('.make_show_search_content').html(REPORT_CREATE.newView.queryHtml);
        REPORT_CREATE.hide();
        $('.create_show_step_3').show();
    });
    $(".create_show_step_5_last").click(function () {
        $(".create_show_show_query_options").html("");
        REPORT_CREATE.hide();
        $('.create_show_step_4').show();
    });
    $(".create_show_step_6_last").click(function () {
        $(".create_show_end_query_options").html("");
        $(".create_show_show_query_options").html(REPORT_CREATE.showView.queryHtml);
        REPORT_CREATE.hide();
        $('.create_show_step_5').show();
    });

};
REPORT_VIEW.module.initFunc[REPORT_VIEW.module.VIEW_CREATED] = funcOfViewCreated;


REPORT_VIEW.REPORT_CONSULTED = {};
var REPORT_RELATION = REPORT_VIEW.REPORT_CONSULTED;
function funcOfRelationUp(){
    var container = document.getElementById('jsoneditor');

    var options = {
        mode: 'tree',
        modes: ['code', 'form', 'text', 'tree', 'view'], // allowed modes
        onError: function (err) {
            alert(err.toString());
        },
        onModeChange: function (newMode, oldMode) {
            console.log('切换模式从', oldMode, '到', newMode);
        }
    };
    var editor = new JSONEditor(container, options, {});
    $.ajax({
        type : "get",
        url  : REPORT_VIEW.baseUrl + "relation/0",
        data : {},
        async : true,
        success : function(data){
            console.log(data);
            REPORT_RELATION.data = data;
            if (REPORT_RELATION.data["relation_data_config"])
            {
                editor.set(JSON.parse(REPORT_RELATION.data["relation_data_config"]));
            }
            else if (REPORT_RELATION.data["relation_data_default"])
            {
                editor.set(JSON.parse(REPORT_RELATION.data["relation_data_default"]));
            }
            else
            {

            }

        }
    });

    $(".relation_load_default").click(function () {
        if (REPORT_RELATION.data["relation_data_default"])
        {
            editor.set(JSON.parse(REPORT_RELATION.data["relation_data_default"]));
            alert("加载成功！");
        }
    });
    $(".relation_load_run").click(function () {
        if (REPORT_RELATION.data["relation_data_config"])
        {
            editor.set(JSON.parse(REPORT_RELATION.data["relation_data_config"]));
            alert("加载成功！");
        }
    });
    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                JSON.parse(str);
                return true;
            } catch(e) {
                console.log(e);
                return false;
            }
        }
    }
    $(".relation_save").click(function () {
        $.ajax({
            type : "put",
            url  : REPORT_VIEW.baseUrl + "relation/0",
            data :  {data:JSON.stringify(
                        {"vid":"0",
                          "relation_data_default":REPORT_RELATION.data["relation_data_default"],
                          "relation_data_config":editor.getText()
                        }
                    )
            },
            async : true,
            success : function(data){
                REPORT_RELATION.data["relation_data_config"] = editor.getText();
                alert("保存成功");
            },
            error: function(e) {
                if (e && e.responseText){
                    alert(e.responseText);
                }
            }
    });
    });
};
REPORT_VIEW.module.initFunc[REPORT_VIEW.module.RELATIONSHIP_UPDATE] =funcOfRelationUp;


REPORT_VIEW.VIEW_DELETED={};
var REPORT_DEL = REPORT_VIEW.VIEW_DELETED;
function funcOfViewDel(){
    REPORT_DEL.data = new Array();
    REPORT_DEL.view = new Object();
    REPORT_DEL.queryAllObj = new Array();
    REPORT_DEL.options= {
        columnDefs             : [],
        rowData                : [],
        enableSorting: true,
        rowHeight: 40,
        colWidth: 100,
        showToolPanel:false,
        suppressColumnVirtualisation:true,
        toolPanelSuppressRowGroups:true,
        toolPanelSuppressValues: true,
        toolPanelSuppressPivots: true,
        toolPanelSuppressPivotMode: true

    };
    REPORT_DEL.refreshData = function (){
        $(".del_show_select_view_options").empty();
        $(".del_show_select_view_options").append("<option value='default'>---请选择---</option>");
        $.get( REPORT_VIEW.baseUrl +"view/list", function(data) {
            REPORT_DEL.data = data;
            console.log(data);
            for (var i =0; i < data.length; i++)
            {
                if (null == data[i]["view_name"])
                {
                    continue;
                }
                $(".del_show_select_view_options").append("<option value='"+data[i]["vid"]+"'>"+data[i]["view_name"]+"</option>");
            }
        });
    }

    REPORT_DEL.refreshData();
    $('.del_show_content').hide();

    var gridDiv = document.querySelector('.del_show_grid');
    new agGrid.Grid(gridDiv, REPORT_DEL.options);
    $(".del_show_confirm_view").click(function () {
        if ($(".del_show_select_view_options").val() == 'default')
        {
            alert("请选择模版")
            return;
        }
        REPORT_DEL.data.map(function (ele){
            if ($(".del_show_select_view_options").val() == ele["vid"]) {
                REPORT_DEL.view = ele;
                console.log("REPORT_DEL.view:" + REPORT_DEL.view);
                if ("" != REPORT_DEL.view["query_ids"]) {
                    REPORT_DEL.queryAllObj = JSON.parse(REPORT_DEL.view["query_ids"]);
                }
                $(".del_show_query_options").html( REPORT_DEL.view["query_html"]);
                REPORT_DEL.options.api.setColumnDefs(JSON.parse(REPORT_DEL.view["cols_of_sub_groups"]));
                REPORT_DEL.options.api.softRefreshView();
            }
        });

        $('.del_show_content').show();
    });

    $(".del_show_search").click(function() {
        var queryOpt = [];
        for (var i =0; i < REPORT_DEL.queryAllObj.length; i++)
        {
            var query_sub_opt = new Object();
            var query_sub_opt_value = new Object();
            var query_id = "#" +  REPORT_DEL.queryAllObj[i]["key"];
            query_sub_opt_value = REPORT_DEL.queryAllObj[i]["value"];
            if (null == $(query_id).val() || '' == $(query_id).val() || 'default' == $(query_id).val())
            {
                continue;
            }
            query_sub_opt["key"]= REPORT_DEL.queryAllObj[i]["key"];
            query_sub_opt_value["value"] = $(query_id).val();
            query_sub_opt["value"] = query_sub_opt_value;
            queryOpt.push(query_sub_opt);
        }

        $.get( REPORT_VIEW.baseUrl +"view/"+REPORT_DEL.view["vid"]+"/query_data", {query_data:JSON.stringify(queryOpt)},function(data){
            REPORT_DEL.options.api.setRowData(data);
            //gridOptions.api.refresh();
        });
    });
    $(".del_show_del_view").click(function () {
        if ($(".del_show_select_view_options").val() == 'default')
        {
            alert("请选择模版")
            return;
        }
        console.log("vid="+$(".del_show_select_view_options").val());
        $.ajax({
            type : "delete",
            url  : REPORT_VIEW.baseUrl + "view/"+ $(".del_show_select_view_options").val(),
            data : {},
            async : false,
            success : function(){
                REPORT_DEL.refreshData();
                $(".del_show_select_view_options").val('default')
                $('.del_show_content').hide();
                alert("删除成功");
            }
        });

    });
};
REPORT_VIEW.module.initFunc[REPORT_VIEW.module.VIEW_DELETED] = funcOfViewDel;


REPORT_VIEW.REPORT_DESIGNED = {};
var REPORT_MAKE = REPORT_VIEW.REPORT_DESIGNED;
function funcOfReportDesign(){
    REPORT_MAKE.data = [];
    REPORT_MAKE.reportData =[];
    REPORT_MAKE.view = new Object();
    REPORT_MAKE.queryAllObj = [];
    REPORT_MAKE.options= {
        columnDefs             : [],
        rowData                : [],
        enableSorting: true,
        rowHeight: 40,
        colWidth: 100,
        showToolPanel:false,
        suppressColumnVirtualisation:true,
        toolPanelSuppressRowGroups:true,
        toolPanelSuppressValues: true,
        toolPanelSuppressPivots: true,
        toolPanelSuppressPivotMode: true

    };
    REPORT_MAKE.refreshData = function (){
        $(".make_show_select_view_options").empty();
        $(".make_show_select_view_options").append("<option value='default'>---请选择---</option>");
        $.get( REPORT_VIEW.baseUrl +"view/list", function(data) {
            REPORT_MAKE.data = data;
            console.log(data);
            for (var i =0; i < data.length; i++)
            {
                if (null == data[i]["view_name"])
                {
                    continue;
                }
                $(".make_show_select_view_options").append("<option value='"+data[i]["vid"]+"'>"+data[i]["view_name"]+"</option>");
            }
        });
    }
    REPORT_MAKE.refreshData();
    $('.make_show_content').hide();

    var gridDiv = document.querySelector('.make_show_grid');
    new agGrid.Grid(gridDiv, REPORT_MAKE.options);
    $(".make_show_select_view_options").change(function(){
        REPORT_MAKE.reportData = [];
        REPORT_MAKE.view = new Object();
        $('.make_show_content').hide();
    });
    $(".make_show_confirm_view").click(function () {
        if ($(".make_show_select_view_options").val() == 'default')
        {
            alert("请选择模版")
            return;
        }
        REPORT_MAKE.data.map(function (ele){
            if ($(".make_show_select_view_options").val() == ele["vid"]) {
                REPORT_MAKE.view = ele;
                console.log("REPORT_MAKE.view:" + REPORT_MAKE.view);
                if ("" != REPORT_MAKE.view["query_ids"]) {
                    REPORT_MAKE.queryAllObj = JSON.parse(REPORT_MAKE.view["query_ids"]);
                }
                $(".make_show_query_options").html( REPORT_MAKE.view["query_html"]);
                REPORT_MAKE.options.api.setColumnDefs(JSON.parse(REPORT_MAKE.view["cols_of_sub_groups"]));
                REPORT_MAKE.options.api.softRefreshView();
            }
        });

        $('.make_show_content').show();
    });

    $(".make_show_search").click(function() {
        var queryOpt = [];
        for (var i =0; i < REPORT_MAKE.queryAllObj.length; i++)
        {
            var query_sub_opt = new Object();
            var query_sub_opt_value = new Object();
            var query_id = "#" +  REPORT_MAKE.queryAllObj[i]["key"];
            query_sub_opt_value = REPORT_MAKE.queryAllObj[i]["value"];
            if (null == $(query_id).val() || '' == $(query_id).val() || 'default' == $(query_id).val())
            {
                continue;
            }
            query_sub_opt["key"]= REPORT_MAKE.queryAllObj[i]["key"];
            query_sub_opt_value["value"] = $(query_id).val();
            query_sub_opt["value"] = query_sub_opt_value;
            queryOpt.push(query_sub_opt);
        }
        $.get( REPORT_VIEW.baseUrl +"view/"+ REPORT_MAKE.view["vid"]+"/query_data", {query_data:JSON.stringify(queryOpt)},function(data){
            REPORT_MAKE.reportData = data;
            REPORT_MAKE.options.api.setRowData(data);
        });
    });


    $(".make_show_save_data").click(function() {
        if (REPORT_MAKE.reportData.length ==0)
        {
            alert("报表数据不能为空");
            return;
        }
        var info = "请输入报表名称";
        var report_name = prompt(info);
        if (report_name == ''){
            alert("报表名称不能为空");
            return;
        }

        var data = new Object();
        data["report_name"] = report_name;
        data["report_data"] = (JSON.stringify(REPORT_MAKE.reportData));
        data["view_for_grid_id"] = REPORT_MAKE.view["vid"];
        $.ajax({
            type : "post",
            url :  REPORT_VIEW.baseUrl + "report/new",
            data: {data:JSON.stringify(data)},
            async : true,
            success : function(data){
                alert("保存成功");
            }
        });
    });
    $(".make_show_excel").click(function() {
        if (""== $(".make_show_excel_file_name").val())
        {
            alert("请输入文件名");
            return;
        }
        REPORT_MAKE.options.api.exportDataAsExcel({
            skipHeader: false,
            columnGroups: false,
            skipFooters: false,
            skipGroups: false,
            skipFloatingTop: false,
            skipFloatingBottom: false,
            allColumns: false,
            onlySelected: false,
            fileName: $(".make_show_excel_file_name").val()
        });
    });
};
REPORT_VIEW.module.initFunc[REPORT_VIEW.module.REPORT_DESIGNED] =funcOfReportDesign;


REPORT_VIEW.REPORT_CONSULTED = {};
var REPORT_READ = REPORT_VIEW.REPORT_CONSULTED;
function funcOfReportConsult(){
REPORT_READ.data = new Array();
REPORT_READ.view = new Object();
REPORT_READ.queryAllObj = new Array();
REPORT_READ.options= {
    columnDefs             : [],
    rowData                : [],
    enableSorting: true,
    enableColResize:true,
    rowHeight: 40,
    colWidth: 100,
    showToolPanel:false,
    suppressColumnVirtualisation:true,
    toolPanelSuppressRowGroups:true,
    toolPanelSuppressValues: true,
    toolPanelSuppressPivots: true,
    toolPanelSuppressPivotMode: true,
};
REPORT_READ.refreshData = function (){
    $(".all_show_select_report_options").empty();
    $(".all_show_select_report_options").append("<option value='default'>---请选择---</option>");
    $.get( REPORT_VIEW.baseUrl +"report/list", function(data) {
        REPORT_READ.data = data;
        console.log(data);
        for (var i =0; i < data.length; i++)
        {
            if (null == data[i]["report_name"])
            {
                continue;
            }
            $(".all_show_select_report_options").append("<option value='"+data[i]["vid"]+"'>"+data[i]["report_name"]+"</option>");
        }
    });
    $.get( REPORT_VIEW.baseUrl +"view/list", function(data) {
        REPORT_READ.view.data = data;
    });
};
    REPORT_READ.refreshData();
    $('.all_show_content').hide();

    var gridDiv = document.querySelector('.all_show_grid');
    new agGrid.Grid(gridDiv, REPORT_READ.options);
    $(".all_show_select_report_options").change(function(){
        $('.all_show_content').hide();
    });
    $(".all_show_confirm_report").click(function () {
        if ($(".all_show_select_report_options").val() == 'default')
        {
            alert("请选择报表")
            return;
        }

        var report_gird_id = '';
        REPORT_READ.data.map(function (ele){
            if ($(".all_show_select_report_options").val() == ele["vid"]) {
                report_gird_id = ele["view_for_grid_id"];
            }
        });
        if (report_gird_id =='')
        {
            alert("报表模版错误")
            return;
        }
        var grid = new Object();
        REPORT_READ.view.data.map(function (ele){
            if (report_gird_id == ele["vid"]) {
                grid = ele;
                console.log("grid:" + grid);

                REPORT_READ.options.api.setColumnDefs(JSON.parse(grid["cols_of_sub_groups"]));

                //var allColumnIds = [];
                //(JSON.parse(grid["cols_of_sub_groups"])).forEach( function(columnDef) {
                //    allColumnIds.push(columnDef.field);
                //});
                //REPORT_READ.options.columnApi.setColumnsVisible(allColumnIds,true);
                REPORT_READ.options.api.refreshView();
                //REPORT_READ.options.api.sizeColumnsToFit();

            }
        });
        $('.all_show_content').show();
        $.ajax({
            type : "get",
            url  : REPORT_VIEW.baseUrl + "report/"+ $(".all_show_select_report_options").val(),
            data : {},
            async : true,
            success : function(data){
                REPORT_READ.options.api.setRowData(JSON.parse(data["report_data"]));
                //REPORT_READ.options.columnApi.autoSizeColumns(allColumnIds);
            }
        });

    });


};
REPORT_VIEW.module.initFunc[REPORT_VIEW.module.REPORT_CONSULTED] = funcOfReportConsult;

$(document).ready(function() {
    console.log("init main js");
    var set_url = "rp_base_url_value";
    if ("rp_base_url_value" != set_url)
    {
        REPORT_VIEW.baseUrl = set_url;
    }

    REPORT_VIEW.module.all =[];
    REPORT_VIEW.module.all.push(REPORT_VIEW.module.VIEW_CREATED);
    REPORT_VIEW.module.all.push(REPORT_VIEW.module.RELATIONSHIP_UPDATE);
    REPORT_VIEW.module.all.push(REPORT_VIEW.module.VIEW_DELETED);
    REPORT_VIEW.module.all.push(REPORT_VIEW.module.REPORT_DESIGNED);
    REPORT_VIEW.module.all.push(REPORT_VIEW.module.REPORT_CONSULTED);


    REPORT_VIEW.module.all.map(function(div){
      $('.'+div).hide();
    });

    $.ajax({
        type : "get",
        url  : REPORT_VIEW.baseUrl + "data/base",
        data : {},
        async: true,
        success : function(data){
            console.log("init main data:");
            console.log(data);
            REPORT_VIEW.module.allow =[];
            REPORT_VIEW.module.allow = data.module;
            REPORT_VIEW.route        = data.route;

            REPORT_VIEW.module.allow.map(function(ele){
                //init module func
                var report_view_ng_html ="";
                if (REPORT_VIEW.module.all.indexOf(ele) >=0)
                {
                   report_view_ng_html+=REPORT_VIEW.module.DIV[ele];
                }
                $('.index_ng_content').append(report_view_ng_html);
            });

            REPORT_VIEW.module.allow.map(function(ele){
             //init module func
             console.log("init Module "+ ele);
             $('.ng_'+ ele).click(function(){
                  REPORT_VIEW.module.initFunc[ele]();
                  REPORT_VIEW.module.all.map(function(div){
                    $('.'+div).hide();
                    console.log("div:"+div);
                  });
                 var ele_name = ele;
                 console.log(" elename: ");
                 console.log($('.'+ ele_name));

                 $('.'+ ele_name).show();
              });

            });
        }
    });

});